package com.dongdong.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class ShiroConfig {
    /*
    * 创建ShiroFilterFactoryBean
    * */
    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        Map<String,String> fileMap = new LinkedHashMap<>();
        fileMap.put("/shopLogin/**","anon");
        fileMap.put("/css/**","anon");
        fileMap.put("/img/**","anon");
        fileMap.put("/js/**","anon");
        fileMap.put("/plugins/**","anon");

//        fileMap.put("/tPerson/toInfoLogin","anon");
//        fileMap.put("/menu/getInfo","perms[menu_perm]");//permissions 权限
//        fileMap.put("/role/getRole","perms[role_perm]");//permissions 权限
//        fileMap.put("/tPerson/getShow","perms[tPerson_perm]");//permissions 权限
//        fileMap.put("/role/toAdd","perms[role:add]");//permissions 权限

        //退出
        fileMap.put("/logout","logout");
        //拦截所有
//        fileMap.put("/**","authc");
        //调整登录页面
        shiroFilterFactoryBean.setLoginUrl("/tPerson/getLogin");
        //没有权限跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorizedUrl");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(fileMap);
        shiroFilterFactoryBean.setSecurityManager( defaultWebSecurityManager());
        return shiroFilterFactoryBean;
    }
    /*
    * 创建DefaultWebSecurityManager 安全管理器
    * */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(getRealm());
        return securityManager;
    }
    //创建realm
    @Bean
    public UserRealm getRealm(){
        UserRealm userRealm = new UserRealm();
      //设置加密方式
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return  userRealm;
    }
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
       //加密方式
        matcher.setHashAlgorithmName("MD5");
        //设置加密编码格式
        matcher.setStoredCredentialsHexEncoded(true);
        //设置加密次数
        matcher.setHashIterations(5);
        return matcher;
    }
   // thymeleaf 整合  shiro功能
    @Bean
    public ShiroDialect shiroDialect(){
        return  new ShiroDialect();
    }


}
